/**
 * 过滤器
 * */
package org.zmhhxl.sample3.oauth2.a.filter;

//DefaultLoginPageGeneratingFilter.java

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.WebUtils;

import java.io.IOException;

/**
 * This filter sets the X-XSRF-TOKEN header with the token value
 * 这个过滤器用令牌值设置X-XSRF-TOKEN报头
 * Spring Security 6 doesn't set a XSRF-TOKEN cookie by default.
 * This solution is
 * <a href="https://github.com/spring-projects/spring-security/issues/12141#issuecomment-1321345077">
 * recommended by Spring Security.</a>
 */
public class CookieCsrfFilter extends OncePerRequestFilter {
   /**
    * {@inheritDoc}
    */
   @Override
   protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                   FilterChain filterChain) throws ServletException, IOException {
      CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());

      if (csrfToken != null) {
         Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
         String token = csrfToken.getToken();
         if (cookie == null || token != null && !token.equals(cookie.getValue())) {
            cookie = new Cookie("XSRF-TOKEN", token);
            cookie.setPath("/");
            response.addCookie(cookie);
         }
         response.setHeader(csrfToken.getHeaderName(), csrfToken.getToken());
      }

      filterChain.doFilter(request, response);
   }
}
